/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jsonHelper.SimpleUniverse;
import service.MumuUser;
import service.MumuUserFacadeREST;
import service.Universe;
import service.UniverseFacadeREST;
import session.UserData;

/**
 *
 * @author andrew
 */
@WebServlet(name = "deleteUniverseServlet", urlPatterns = {"/deleteUniverseServlet"})
public class deleteUniverseServlet extends HttpServlet {

    @EJB
    UniverseFacadeREST universeManager;
    
    @EJB
    MumuUserFacadeREST userManager;
    
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
       // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {} 
//        else {
//            response.sendRedirect("/home.jsp");
//        } 
        
       String idUniverseString = request.getParameter("u");
       //System.out.print("valore pas: "+idUniverseString);
        int idUniverse = Integer.parseInt(idUniverseString);
        
        Universe universe = universeManager.find(idUniverse);
        universeManager.remove(universe);
        
        // cancellazione in filesystem della cartella Universo associata
        File directory = new File(request.getServletContext().getRealPath("/")+"Universes/"+idUniverse);
        
        //verifica se la directory esiste
    	if(!directory.exists()){
           System.out.println("Directory does not exist.");
        }else{

           try{ 
               delete(directory);
           }catch(Exception e){}
        }
 
    	System.out.println("Done");    
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // check if session is expired
        HttpSession session = request.getSession();// don't create if it doesn't exist
//        if(session != null && !session.isNew()) {} 
//        else {
//            response.sendRedirect("/home.jsp");
//        }
        
        String idUniverseString = request.getParameter("u");
        int idUniverse = Integer.parseInt(idUniverseString);
        
        Universe universe = universeManager.find(idUniverse);
        universeManager.remove(universe);
        
        ArrayList<SimpleUniverse> universeList = (ArrayList<SimpleUniverse>) session.getAttribute("universeList");

        Iterator<SimpleUniverse> simpleUniverseIt = universeList.iterator();
        SimpleUniverse editingUniverse = null;
        int i = 0;
        while (simpleUniverseIt.hasNext()) {
            editingUniverse = simpleUniverseIt.next();
            if (editingUniverse.getIdUniverse() == idUniverse) {
                break;
            }
            i++;
        }
        universeList.remove(i);
        
        // cancellazione in filesystem della cartella Universo associata
        File directory = new File(request.getServletContext().getRealPath("/")+"Universes/"+idUniverse);
        
        //verifica se la directory esiste
    	if(!directory.exists()){
           System.out.println("Directory does not exist.");
        } else {
           try{ 
               delete(directory);
           }catch(Exception e){}
        }
 
    	System.out.println("Done. Folder Universe in FileSystem has been deleted");
        
        
        // cancellazione zip della cartella Universo associata
        File directoryZip = new File(request.getServletContext().getRealPath("/")+"Universes/"+idUniverse+".zip");
        
        //verifica se la directory esiste
    	if(!directoryZip.exists()){
           System.out.println("DirectoryZip does not exist.");
        } else {
           try{ 
               delete(directoryZip);
           }catch(Exception e){}
        }
 
    	System.out.println("Done. Universe Zip file has been deleted");
        
        
        
        
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
    
    
    
    
    private static void delete(File file) throws IOException{
 
    	if(file.isDirectory()){
 
    		//directory è vuota, quindi si può cancellare
    		if(file.list().length==0){
    		   file.delete();
    		   System.out.println("Directory is deleted : "+ file.getAbsolutePath());
    		}else{
 
    		   //lista di tutte le sottodirectory contenute
        	   String files[] = file.list();
 
        	   for (String temp : files) {
        	      //construttore file
        	      File fileDelete = new File(file, temp);
 
        	      //cancellazione ricorsiva
        	     delete(fileDelete);
        	   }
 
        	   //controllo se directory è vuota e in caso affermativo la rimuovo
        	   if(file.list().length==0){
           	     file.delete();
        	     System.out.println("Directory is deleted : "+ file.getAbsolutePath());
        	   }
    		}
 
    	}else{
    		//se è file lo si cancella
    		file.delete();
    		System.out.println("File is deleted : " + file.getAbsolutePath());
    	}
    }
}
